package cn.wp.basic.controller;

import cn.wp.basic.util.AjaxResult;
import cn.wp.basic.util.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/dfs")
public class FastDfsController {

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = FilenameUtils.getExtension(filename);
            String uploadPath = FastDfsApiOpr.upload(file.getBytes(), extName);

            return AjaxResult.me().setResultObject(uploadPath);
        } catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }

    @DeleteMapping("/del")
    public AjaxResult del(String path){
        try{
            String groupName = path.substring(1,path.indexOf("/", 1));
            String fileName = path.substring((path.indexOf("/", 1)) + 1);
            FastDfsApiOpr.delete(groupName, fileName);
            return new AjaxResult();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg(e.getMessage());
        }
    }
}
